package com.cmge.ad.util.thread;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.cmge.ad.model.Crawl;
import com.cmge.ad.service.CrawlService;
import com.cmge.ad.util.context.SpringContextUtil;

/**
 * @desc	爬虫任务扫描线程  执行器  扫描到的爬虫任务另外开启线程执行
 * @author	ljt
 * @time	2015-1-29 下午3:50:46
 */
public class CrawlerMonitor implements Runnable {

	public static final Logger logger = Logger.getLogger(CrawlerMonitor.class);
	
	private CrawlService crawlService;
	
	public void run() {
		ApplicationContext context = SpringContextUtil.getApplicationContext();
		crawlService = (CrawlService) context.getBean(CrawlService.class);
		
		while (true) {
			// 带宽考虑 每次只取一个爬虫任务
			final Crawl crawl = crawlService.scanCrawlTask();
			if(null != crawl){
				// 开启线程  执行爬虫任务
				new Thread(new Runnable() {
					@Override
					public void run() {
						logger.info("爬虫开始....");
						crawlService.starCralTask(crawl);
						crawlService.runCrawlTask(crawl);
						logger.info("爬虫结束....");
					}
				}).start();
			}
			
			// 休眠10秒
			sleep(10000);
		}
	}
	
	/**
	 * 线程休眠
	 */
	public void sleep(int time){
		try {
			logger.info("线程休眠"+time/1000+"s");
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
